package com.hivis.websocket;

import com.hivis.utils.TokenUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

import java.util.Map;

/**
 * 创建握手（handshake）接口/拦截器
 *
 */
public class MyWebsocketInterceptor extends HttpSessionHandshakeInterceptor {

	@Override
	public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception ex) {
		super.afterHandshake(request, response, wsHandler, ex);
	}

	@Override
	public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {

		String token =  ((ServletServerHttpRequest) request).getServletRequest().getParameter("token");
		String notebookId =  ((ServletServerHttpRequest) request).getServletRequest().getParameter("notebookId");
		if (StringUtils.isNotEmpty(notebookId)) {
			attributes.put("notebookId", notebookId);
		}
		System.out.println("--------------->进入beforeHandshake");
		// 验证token
//		if (StringUtils.isNotEmpty(token) && TokenUtil.verify(token)) {
//			attributes.put("token", token);
//			String notebookId =  ((ServletServerHttpRequest) request).getServletRequest().getParameter("notebookId");
//			if(StringUtils.isNotEmpty(notebookId)){
//				attributes.put("notebookId", notebookId);
//			}
//			return super.beforeHandshake(request, response, wsHandler, attributes);
//		} else {
//			return false;
//		}
//		if(StringUtils.isNotEmpty(UserUtils.getUser().getUsername())){
//			attributes.put("user", UserUtils.getUser());
//			return super.beforeHandshake(request, response, wsHandler, attributes);
//		}else {
//			return false;
//		}
		return true;
	}

}
